<template>
    <div class="topic-list" ref="listContainer">
        <el-table :data="topics" style="width: 100%" :height="tableHeight">
            
            <!-- 题目标题列 -->
            <el-table-column prop="title" label="题目" min-width="400" fixed>
                <template #default="{ row }">
                    <router-link :to="`/baguwen/detail/${row.id}?subject_id=${row.id}`" class="topic-title"
                        target="_blank">
                        {{ row.title }}
                    </router-link>
                </template>
            </el-table-column>

            <!-- 难度列 -->
            <el-table-column prop="difficult" label="难度" width="100">
                <template #default="{ row }">
                    <el-tag :type="getDifficultyType(row.difficult)">
                        {{ getDifficultyLabel(row.difficult) }}
                    </el-tag>
                </template>
            </el-table-column>

            <!-- 标签列 -->
            <el-table-column label="标签" min-width="200">
                <template #default="{ row }">
                    <div class="tag-group">
                        <el-tag v-for="tag in row.labels" :key="tag" class="topic-tag" size="small" effect="plain">
                            {{ tag }}
                        </el-tag>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 替换分页器为加载提示 -->
        <div class="loading-more" v-if="hasMore">
            <el-text class="loading-text" v-if="loading">加载中...</el-text>
        </div>
    </div>
</template>

<script setup lang="ts">
import { useTopicStores } from '@/stores/topicStores'
import { storeToRefs } from 'pinia'
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'

const topics = ref<Array<any>>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const hasMore = ref(true)
const listContainer = ref<any>(null)
const route = useRoute()

const topicStores = useTopicStores();
const { getCurrentSubject } = topicStores;
const { currentSubjectList } = storeToRefs(topicStores);

const types: { [key: number]: string } = {
    1: 'success',  // 简单
    2: 'warning',  // 中等
    3: 'danger'    // 困难
}

const labels: { [key: number]: string } = {
    1: '简单',
    2: '中等',
    3: '困难'
}

// 添加一个变量存储当前的搜索条件
const currentSearchParams = ref({})

// 添加表格高度计算
const tableHeight = ref('calc(80vh - 40px)') // 减去padding的高度(上下各20px)


// 获取难度标签类型
const getDifficultyType = (difficult: number) => {
    return types[difficult] || 'info'
}

// 获取难度标签文本
const getDifficultyLabel = (difficult: number) => {
    return labels[difficult] || ''
}

// 加载题目列表
const loadTopics = async (params: any = {}) => {
    if (loading.value || !hasMore.value) return

    try {
        loading.value = true
        const categoryId = route.query.category_id
        const searchParams = {
            ...params,
            categoryIdList: params.categoryIdList || (categoryId ? [Number(categoryId)] : null),
            ...currentSearchParams.value
        }
        if (!searchParams.categoryIdList && !searchParams.detail && !searchParams.difficult) {
            if (!categoryId) {
                console.warn('没有可用的分类ID')
                return
            }
            searchParams.categoryIdList = [Number(categoryId)]
        }

        await getCurrentSubject(searchParams, currentPage.value, pageSize.value);
        
        if (currentSubjectList.value) {
            // 追加数据
            topics.value = [...topics.value, ...currentSubjectList.value.records.map(item => ({
                id: item.id,
                title: item.detail,
                difficult: item.difficult,
                labels: [...(item.subjectCategoryList || []), ...(item.subjectLabelList || [])]
            }))];
            
            total.value = currentSubjectList.value.total;
            hasMore.value = topics.value.length < total.value
            currentPage.value++
        }

    } catch (error) {
        console.error('获取题目列表失败：', error)
    } finally {
        loading.value = false
    }
}

// 滚动监听处理
const handleScroll = () => {

    if (!listContainer.value) return

    const containerRect = listContainer.value.getBoundingClientRect()
    const bottomOffset = containerRect.bottom - window.innerHeight

    // 当距离底部100px时触发加载
    if (bottomOffset < 100 && !loading.value && hasMore.value) {
        loadTopics()
    }
}

// 重置数据列表
const resetList = (params = {}) => {
    topics.value = []
    currentPage.value = 1
    hasMore.value = true
    total.value = 0
    // 使用传入的参数调用 loadTopics，如果没有参数则使用默认值
    loadTopics(params)
}


// 搜索结果处理函数
const handleSearchResult = (result:any) => {
    const { data, params } = result;

    const { categoryIdList, detail, difficult, type, score } = params;


    currentSearchParams.value = { categoryIdList, detail, difficult, type, score };
    // 重置分页相关状态
    currentPage.value = 1;
    topics.value = data.records.map((item:any) => ({
        id: item.id,
        title: item.detail,
        difficult: item.difficult,
        labels: [...(item.categoryNames || []), ...(item.labelNames || [])]
    }))
    total.value = data.total
    hasMore.value = topics.value.length < total.value
    // 如果还有更多数据，将页码设置为下一页
    if (hasMore.value) {
        currentPage.value = 2; // 修改为2，因为第一页数据已经加载完成
    }
}


onMounted(() => {
    loadTopics()
    listContainer.value ? listContainer.value.addEventListener('scroll', handleScroll) : null;
    window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
    listContainer.value ? listContainer.value.removeEventListener('scroll', handleScroll) : null;
    window.removeEventListener('scroll', handleScroll)
})

defineExpose({
    handleSearchResult,
    resetList
})

</script>

<style scoped>
.topic-list {
    background-color: white;
    border-radius: 8px;
    padding: 20px;
    margin-top: 20px;
    max-height: 80vh;
    /* 修改这行，从max-height改为height */
    overflow-y: auto;
}

.topic-title {
    color: #409eff;
    text-decoration: none;
    font-weight: 500;
}

.topic-title:hover {
    color: #66b1ff;
    text-decoration: underline;
}

.tag-group {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.topic-tag {
    margin-right: 4px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.loading-more {
    text-align: center;
    margin-top: 20px;
    padding: 10px 0;
}

.loading-text {
    color: #909399;
    font-size: 14px;
}
</style>